import { MaterialIcons } from '@expo/vector-icons';
import React, { useMemo } from 'react';
import {
  Dimensions,
  Modal,
  Pressable,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

type MenuKey = 'photo' | 'sticker' | 'background' | 'text';

interface CanvasMenuProps {
  visible: boolean;
  position: { x: number; y: number };
  onClose: () => void;
  onSelectPhoto: () => void;
  onSelectSticker: () => void;
  onSelectBackground: () => void;
  onSelectText: () => void;
  onlyKeys?: MenuKey[]; // 可选：限制显示的菜单项
}

const menuItems: { key: MenuKey; label: string; icon: any }[] = [
  { key: 'photo', label: '相册', icon: 'photo-library' },
  { key: 'sticker', label: '贴纸', icon: 'emoji-emotions' },
  { key: 'background', label: '背景', icon: 'image' },
  { key: 'text', label: '文字', icon: 'text-fields' },
];

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

export const CanvasMenu: React.FC<CanvasMenuProps> = ({
  visible,
  position,
  onClose,
  onSelectPhoto,
  onSelectSticker,
  onSelectBackground,
  onSelectText,
  onlyKeys,
}) => {
  // 计算菜单的安全位置，确保不超出屏幕
  const safePosition = useMemo(() => {
    const menuWidth = 150; // 菜单宽度（更新以适应15px间距）
    const currentItems = onlyKeys ? menuItems.filter((m) => onlyKeys.includes(m.key)) : menuItems;
    const menuHeight = currentItems.length * 50 + 30; // 菜单项高度 * 项目数量 + 上下padding
    const padding = 15; // 安全边距

    let x = position.x;
    let y = position.y;

    // 检查右边界
    if (x + menuWidth > screenWidth - padding) {
      x = screenWidth - menuWidth - padding;
    }

    // 检查左边界
    if (x < padding) {
      x = padding;
    }

    // 检查下边界
    if (y + menuHeight > screenHeight - padding) {
      y = screenHeight - menuHeight - padding;
    }

    // 检查上边界
    if (y < padding) {
      y = padding;
    }

    return { x, y };
  }, [position.x, position.y, onlyKeys]);

  const handleItemPress = (key: string) => {
    switch (key) {
      case 'photo':
        onSelectPhoto();
        break;
      case 'sticker':
        onSelectSticker();
        break;
      case 'background':
        onSelectBackground();
        break;
      case 'text':
        onSelectText();
        break;
    }
    onClose();
  };

  if (!visible) return null;

  return (
    <Modal transparent visible={visible} animationType="fade">
      <Pressable style={styles.overlay} onPress={onClose}>
        <View style={[styles.menu, { top: safePosition.y, left: safePosition.x }]}>
          {(onlyKeys ? menuItems.filter((m) => onlyKeys.includes(m.key)) : menuItems).map((item) => (
            <TouchableOpacity
              key={item.key}
              style={styles.menuItem}
              onPress={() => handleItemPress(item.key)}
            >
              <MaterialIcons name={item.icon} size={20} color="#333" />
              <Text style={styles.menuItemText}>{item.label}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </Pressable>
    </Modal>
  );
};

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  menu: {
    position: 'absolute',
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15, // 应用15px间距规范
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
    minWidth: 120,
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 15, // 应用15px间距规范
    paddingHorizontal: 15, // 应用15px间距规范
  },
  menuItemText: {
    marginLeft: 15, // 应用15px间距规范
    fontSize: 14,
    color: '#333',
  },
});
